#include<iostream>
#include<pthread.h>
#include<unistd.h>
using namespace std;

int capacity = 1000;

pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;

void* BuyTicket(void* input)
{
    char* ch = static_cast<char*>(input);
    while(true)
    {
        pthread_mutex_lock(&mylock);
        if(capacity >= 0)
        {
            usleep(1000);
            printf("%s买票:%d\n",ch,capacity);
            capacity--;
            pthread_mutex_unlock(&mylock);
        }
        else
        {
            pthread_mutex_unlock(&mylock);
            break;
        }
    }

    return nullptr;
}

int main()
{
    pthread_t t1;
    pthread_t t2;
    pthread_t t3;
    pthread_t t4;
    
    pthread_create(&t1,nullptr,BuyTicket,(void*)"thread1");
    pthread_create(&t2,nullptr,BuyTicket,(void*)"thread2");
    pthread_create(&t3,nullptr,BuyTicket,(void*)"thread3");
    pthread_create(&t4,nullptr,BuyTicket,(void*)"thread4");


    pthread_join(t1,nullptr);
    pthread_join(t2,nullptr);
    pthread_join(t3,nullptr);
    pthread_join(t4,nullptr);

    return 0;
}
